import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Layout,List, Divider  ,Table, Select, Space,
    Button,Modal,Form, Input, Row ,Col,
    Checkbox,Tree,message,Avatar } from 'antd';
import {dataObjInitQuery} from "../api/dataObject";
import {getDims,getDims2,delDimMbr,getTheMbr,getDimMbrs} from "../api/dim";
import { ArrowRightOutlined } from '@ant-design/icons';
export default class CaDataObject extends Component {

    constructor(props) {
        super(props)
        this.state = {
            dims:[],  //维度对象集合
            currentDim:{},  //当前维度
            dimMbrs:[],//dimession members
            caDataObjectDims:[], //数据对象维度{dimId:dim,member[]:members}
            caDataObjectMbrs:[]  //members
        }
    }

    onChange = (e) => {
        this.setState({ value: e.target.value })
    }

    componentDidMount() {
        dataObjInitQuery().then(
            (res) => {
                this.setState({dims: res.data.dims_cube.cube_101,
                    currentDim:res.data.dims_cube.cube_101[0],
                    dimMbrs:res.data.init_MbrsTree.children
                });
            },
            (error) => {
                console.log("get response failed!");
            }
        );
    }

     onSelect = (selectedKeys, info) => {
        console.log('selected', selectedKeys, info);
    };

    drop=(event)=>
    {
        let _dims=this.state.caDataObjectDims;
        let _currentDim=this.state.currentDim;
        let  memberName=event.dataTransfer.getData('memberName');
        let  memberId=event.dataTransfer.getData('memberId');
        //当前维度是否已经存在
        let _i=_dims.findIndex((item)=>item.id==_currentDim.id)

        if(_i==-1){ // new dimession +new dimession member
            _dims.push({..._currentDim,members:[{memberId:memberId,memberName:memberName}]});
           // _dims.push({..._currentDim,members:[{memberId:999,memberName:"txssss"}]});

        }else{  //new member
            //判断成员的维度信息信息  找到对应的维度容器  判断该容器内是否有该维度成员  如果没有 则添加
            let _targetDimMbrs=_dims[_i].members;

            let _j=_targetDimMbrs.findIndex((item)=>item.memberId==memberId)
            if(_j==-1){ // add
                _targetDimMbrs.push({memberId:memberId,memberName:memberName});

            }else{
                message.error("该维度成员选择过了")
            }
        }
        this.setState({caDataObjectDims:_dims})
    }

//移出维度列表
    removeTheDimList=(dimId,that)=>{
        console.log(dimId);
        //remove the dimList  从集合当中删除
        let _r=that.state.caDataObjectDims.splice(that.state.caDataObjectDims.findIndex(item => item.id === dimId), 1);
        let _p=that.state.caDataObjectDims;
        that.setState({_p,_r});
        console.log(_r);
    }


    /**
     *
     * 移出维度成员
     * 找到当前dim Id
     * 找到当前集合中memberId,且移出
     *
     * @param dimId
     * @param memberId
     * @param that
     */
    removeDimMbrItem=(dimId,memberId,that)=>{
        //从集合当中remove
        let _dims=that.state.caDataObjectDims;
        let _i=_dims.findIndex((item)=>item.id==dimId);
        //查找后,
        if(_i>-1){  //找到了
            let _targetDimMbrs=_dims[_i].members;
            let _j=_targetDimMbrs.findIndex((item)=>item.memberId==memberId)
            if(_j>=0){ // remove  item
                _targetDimMbrs.splice(_j, 1);
                let _r=that.state.caDataObjectDims;
                let _p=that.state.caDataObjectDims;
                that.setState({_p,_r})
            }else{
                message.info("没找到维度成员")
            }
        }else{
            message.info("没找到维度")
        }
    }


    render() {
        const { Header, Footer, Sider, Content } = Layout;
        const { Option } = Select;
        const layoutStyle={
            height:"100%"
        }

        function handleChange(value) {
            console.log(`selected ${value}`);
        }
        // change dimession
        let _that=this;
        const handleChangeDim=(value)=> {
            console.log(`selected ${value}`);

            //find dim object by dimid

            let _curentDims = this.state.dims.filter(function (obj) {
                return obj.id ===value
            })
            this.setState({currentDim:_curentDims[0]})
            console.log(this.state.currentDim.name)

            getDimMbrs(value).then(
                (res) => {
                    _that.setState({dimMbrs: res.data.children
                    });
                },
                (error) => {
                    console.log("get response failed!");
                }
            );
        }

        //拖动的时候，是这个事件吗
        const onDrop = (event) => {
            event.event.dataTransfer.setData('memberName', event.node.text);
            event.event.dataTransfer.setData('memberId', event.node.id);
        }


        function allowDrop(event){
            event.preventDefault();
        };




        const data = [
            'Racing car sprays burning fuel into crowd.',
            'Japanese princess to wed commoner.',
            'Australian walks 100km after outback crash.',
            'Man charged over missing wedding girl.',
            'Los Angeles battles huge wildfires.',
        ];

        return (
                <Layout style={{height:"100%"}}>
                    <Sider style={{background:"#ffffff",display:"flex"}}>
                        <Row style={{height:"10px"}}>  </Row>
                        <Row justify="center">
                            <Select defaultValue="101" style={{ width: 180 }} onChange={handleChange}>
                                <Option value="101">模型一</Option>
                            </Select>
                        </Row>
                        <Row style={{height:"10px"}}>  </Row>

                        <Row justify="center">

                            <Select defaultValue={111} style={{ width: 180 }} onChange={handleChangeDim}>
                                {
                                    this.state.dims.map((item,index)=>{
                                        return (
                                            <Option value={ item.id } key={ item.id}>{ item.name }</Option>
                                        )
                                    })
                                }
                            </Select>

                        </Row>

                        <Row style={{height:"10px"}}>  </Row>

                        <Row  style={{ position: "absolute",top:"100px" ,bottom:"2px" ,left:"1px",right:"1px",overflow:"scroll"}}>
                            <Tree
                                // onSelect={this.onSelect}
                                treeData={this.state.dimMbrs}
                                draggable
                                //onDrop={onDrop}
                                onDragStart={onDrop}
                            />
                        </Row>
                    </Sider>
                    <Content  style={{borderLeft:"thick double #00ccff"}}>
                        <div  style={{height:"100%",width:"100%",display: "flex"}} onDrop={this.drop} onDragOver={allowDrop}>

                            {this.state.caDataObjectDims.map((dim, index) => {
                                return (
                                    <List
                                        size="small"
                                        header={<div>{dim.name}</div>}
                                        key={dim.id}
                                        itemLayout="vertical"
                                        footer={<div><Button onClick={()=>this.removeTheDimList(dim.id,this)}>移出</Button></div>}
                                        bordered
                                        dataSource={dim.members}
                                        renderItem={item => (
                                            <List.Item actions={[<Button type="link"
                                                                         onClick={()=>this.removeDimMbrItem(dim.id,item.memberId,this)}
                                                                         key="list-remove">remove</Button>]}>
                                                <List.Item.Meta
                                                    avatar={<ArrowRightOutlined />}
                                                    title={item.memberName}
                                                />
                                            </List.Item>
                                        )}
                                        style={{width:200,margin:20}}
                                    />
                                )
                            })
                            }
                        </div>
                    </Content>
                </Layout>
        );
    }
}
